package com.project.petLossSystem.controller.system;

import com.project.petLossSystem.po.ContactItem;
import com.project.petLossSystem.service.ContactItemService;
import com.project.petLossSystem.service.UserService;
import com.project.petLossSystem.util.Result;
import com.project.petLossSystem.util.ResultGenerator;
import com.project.petLossSystem.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class SystemContactItemController {
    @Autowired
    private ContactItemService contactItemService;

    @Autowired
    private UserService userService;

    /**
     * 访问联系方式
     */
    @GetMapping("/contact/{userId}")
    @ResponseBody
    public Result contact(@PathVariable("userId") Long userId, HttpSession session) {
        if (ObjectUtils.isEmpty(userId)) {
            return ResultGenerator.failureResult("参数异常！");
        }
        Long currentUserId = ((UserVO) session.getAttribute("user")).getUserId();
        // 判断是不是本人访问自己帖子，如果是就直接返回session的
        if (currentUserId.equals(userId)) {
            return ResultGenerator.successResult(session.getAttribute("user"));
        }
        // 先查询数据再插入事件，防止对方id不存在
        UserVO userVO = userService.getUserMessage(userId);
        if (ObjectUtils.isEmpty(userVO)) {
            return ResultGenerator.failureResult("用户数据不存在！");
        }
        ContactItem contactItem = new ContactItem();
        contactItem.setUserId(currentUserId);
        contactItem.setContactUserId(userId);
        if (contactItemService.insertItem(contactItem)) {
            return ResultGenerator.successResult(userVO);
        } else {
            return ResultGenerator.failureResult("查看联系方式失败！");
        }
    }
}
